<template>
  <scroll-view
    class="h-screen"
    scroll-y
    :refresher-triggered="refreshing"
    refresher-enabled
    @refresherrefresh="onRefresh"
    @scrolltolower="onReachBottom"
  >
    <UniAdminPanel
      ref="panelRef"
      :fetcher="fetcher"
      @add="onAdd"
      @edit="onEdit"
      @delete="onDelete"
    >
      <!-- 筛选 -->
      <template #filters>
        <view class="flex items-center gap-2">
          <wd-input
            v-model="filters.name"
            placeholder="请输入姓名"
            clearable
            class="flex-1"
          />
          <wd-button type="success" size="small" @click="applyFilters"
            >搜索</wd-button
          >
          <wd-button size="small" plain @click="resetFilters">重置</wd-button>
        </view>
      </template>

      <!-- 列表项 -->
      <template #item="{ row }">
        <view
          class="p-3 rounded-xl bg-white shadow-sm flex justify-between items-center"
        >
          <view class="flex items-center flex-1 gap-3">
            <image
              :src="row.head || '../../static/defluat_head.png'"
              class="w-[100rpx] h-[100rpx] rounded-[50%] bg-gray-200"
              mode="widthFix"
            />
            <view>
              <view class="font-medium text-base">{{ row.name }}</view>
              <view class="text-sm text-gray-500">手机号：{{ row.phone }}</view>
              <view class="text-sm text-gray-400 mt-1"
                >创建时间：{{ row.created_at }}</view
              >
            </view>
          </view>
          <view class="flex gap-2 ml-3">
            <wd-button size="small" type="primary" plain @click="onEdit(row)"
              >编辑</wd-button
            >
            <wd-button size="small" type="error" plain @click="onDelete(row)"
              >删除</wd-button
            >
          </view>
        </view>
      </template>
    </UniAdminPanel>
  </scroll-view>

  <!-- 弹层 -->
  <wd-overlay v-model:show="showForm" position="center" :maskClosable="false">
    <view class="wrapper">
      <view class="w-[85%] bg-white rounded-xl flex flex-col px-4 py-6">
        <view class="text-lg font-bold mb-4 text-center">{{ formTitle }}</view>

        <wd-form ref="formRef" :model="formModel">
          <wd-cell-group border>
            <wd-input
              label="手机号"
              label-width="90px"
              v-model="formModel.phone"
              clearable
              placeholder="请输入手机号"
              :rules="[{ required: true, message: '请填写手机号' }]"
            />
            <wd-input
              label="姓名"
              label-width="90px"
              v-model="formModel.name"
              clearable
              placeholder="请输入姓名"
              :rules="[{ required: true, message: '请填写姓名' }]"
            />
            <wd-input
              label="密码"
              label-width="90px"
              type="password"
              v-model="formModel.password"
              clearable
              placeholder="请输入新密码"
            />
          </wd-cell-group>

          <view class="flex justify-end gap-2 mt-4">
            <wd-button size="small" plain @click="showForm = false"
              >取消</wd-button
            >
            <wd-button type="primary" size="small" @click="handleSubmit"
              >保存</wd-button
            >
          </view>
        </wd-form>
      </view>
    </view>
  </wd-overlay>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import UniAdminPanel from '@/components/Table/tableComponet.vue'
import { useToast } from 'wot-design-uni'
import { adminList, addADmin, updateAdmin, deleteAdmin } from '@/api/admin'

const { success: showSuccess } = useToast()
const panelRef = ref<any>(null)
const refreshing = ref(false)

const filters = reactive({ name: '' })

// 弹窗控制
const showForm = ref(false)
const formTitle = ref('')

// 表单模型
const formModel = reactive<IAdmin>({
  id: 0,
  phone: '',
  name: '',
  password: '',
  head: '',
  created_at: ''
})

const formRef = ref<any>(null)

// 拉取数据
const fetcher = async ({ page = 1, size = 10 }: any) => {
  try {
    const res = await adminList({
      page,
      pageSize: size,
      name: filters.name
    })
    const { items, total } = res.data
    return { items, hasMore: page * size < total }
  } catch (error) {
    console.error('加载管理员失败：', error)
    uni.showToast({ title: '加载失败', icon: 'none' })
    return { items: [], hasMore: false }
  }
}

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true
  await panelRef.value?.refresh()
  refreshing.value = false
}

// 触底加载
const onReachBottom = () => panelRef.value?.loadMore()

// 搜索 / 重置
const applyFilters = () => panelRef.value?.refresh()
const resetFilters = () => {
  filters.name = ''
  panelRef.value?.refresh()
}

// 新增
const onAdd = () => {
  formTitle.value = '新增管理员'
  Object.assign(formModel, {
    id: 0,
    phone: '',
    name: '',
    password: '',
    head: '',
    created_at: ''
  })
  showForm.value = true
}

// 编辑
const onEdit = (row: IAdmin) => {
  formTitle.value = '编辑管理员'
  Object.assign(formModel, {
    id: row.id,
    phone: row.phone,
    name: row.name,
    password: '' // ❗ 不回显密码
  })
  showForm.value = true
}

// 删除
const onDelete = (row: IAdmin) => {
  uni.showModal({
    title: '删除管理员',
    content: `确定删除管理员 ${row.name} 吗？`,
    success: async (res: any) => {
      if (res.confirm) {
        try {
          await deleteAdmin({ id: row.id })
          showSuccess({ msg: '删除成功' })
          panelRef.value?.refresh()
        } catch (error) {
          console.error('删除管理员失败：', error)
        }
      }
    }
  })
}

// 保存（新增或编辑）
const handleSubmit = async () => {
  const isEdit = !!formModel.id
  try {
    if (isEdit) {
      await updateAdmin({
        id: formModel.id,
        phone: formModel.phone,
        name: formModel.name,
        password: formModel.password
      })
      showSuccess({ msg: '修改成功' })
    } else {
      await addADmin({
        phone: formModel.phone,
        name: formModel.name,
        password: formModel.password
      })
      showSuccess({ msg: '新增成功' })
    }
    showForm.value = false
    panelRef.value?.refresh()
  } catch (error) {
    console.error('操作管理员失败：', error)
  }
}
</script>

<style scoped lang="scss">
.wrapper {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
